<?php
// +----------------------------------------------------------------------
// | braingoing.com [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.zsb888.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: zsb <807098383@qq.com>
// +----------------------------------------------------------------------
namespace app\api\controller\v1;

use think\Controller;
use think\Request;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use think\Loader;
use think\Db;

class BaseController extends Controller
{
    public $checkSign = true;
    public $noCheckurl = [

    ];
    public $failure_time=7200;

    public function _initialize(Request $request = null)
    {

        parent::_initialize();
        // TODO: Change the autogenerated stub
        if (is_null($request)) {
            $request = Request::instance();
        }
        $this->request = $request;
        $post_data = $this->request->param();
        $pathinfo=parse_url($this->request->url());
        $uri = $this->request->pathinfo();
        $requestime = $this->request->requestime;//请求时间
        if(!config('app_debug')) {
            if (!in_array($uri, $this->noCheckurl)) {
                $post_data['uri'] = $uri;
                $api_sign = $post_data['sign'];
//               if(time()-$requestime>$this->failure_time){
//                   $this->ajaxReturn(400,'请求超时');
//               }
                $sign = $this->createSign($post_data);

                if ($api_sign != $sign) {
                    $this->ajaxReturn(100, '签名错误');
                }
            }
        }


    }

    /**
     * 生产签名
     */
    protected function createSign($post_data)
    {
        ksort($post_data);
        $salt = config('app_key');

        $params = '';
        foreach ($post_data as $key => $value) {
            $params .= '&' . $key . '=' . $value;
        }
        $pre_sign = substr($params, 1);
        $sign = sha1(md5($salt . $pre_sign));
        return $sign;
    }

    /**
     * 美化参数,并生成符合条件的sn构造出一个新的params,做出类似于客户端app的效果
     * @param $params ['uri']  请求uri,
     * @return array  返回数组
     */
    protected function paramPretty($params)
    {
        $salt = config('app_key');
        if (!isset($params['uri'])) {
            return [
                'status' => false
            ];
        }
        sort($params);
        $_params = "";
        $separator = '';
        foreach ($params as $key => $val) {
            $_params .= $separator . $key . '=' . $val;
            $separator = '&';
        }
        $sign = sha1(md5($salt . $_params));
        return [
            'status' => true,
            'data' => $sign
        ];
    }

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param mixed $msg 提示信息
     * @param mixed $data 返回的数据
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function ajaxReturn($code, $msg = '', $data = [], $force = false, array $header = [])
    {

        $result = [
            'code' => $code,
            'msg' => $msg,
        ];
        if (!empty($data))
            $result = array_merge($result, ['data' => $data]);
        if ($force)
            $result = array_merge($result, ['data' => $data]);
        $type = $this->getResponseType();
        $header['Access-Control-Allow-Origin'] = '*';
        $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type,XX-Device-Type,XX-Token';
        $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
        $response = Response::create($result, $type)->header($header);
        throw new HttpResponseException($response);
    }


    /**
     * 验证数据
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     * @param mixed $callback 回调方法（闭包）
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        if (is_array($validate)) {
            $v = Loader::validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                list($validate, $scene) = explode('.', $validate);
            }
            $v = Loader::validate($validate);
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }
        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        if (is_array($message)) {
            $v->message($message);
        }

        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }

        if (!$v->check($data)) {
            if ($this->failException) {
                throw new ValidateException($v->getError());
            } else {
                return $v->getError();
            }
        } else {
            return true;
        }
    }
}
